<?php
namespace App\Libs\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class YueCaiController extends Controller
{	


    /**
     *悦才请求决策 
     * $type 默认为0   为后台访问
    **/
	public function reDecisionEngine($order_id,$type=0)
    {   
        header("Content-type: text/html; charset=utf-8");
        if($type == 0)
        {
            $row=M("orders")->where("order_id = '$order_id'")->find();
            $param['name']=$row["user_name"];//姓名
            $param['mobile']=$row["user_phone"];//手机号
            $param['id_card_num']=$row["user_id_number"];//身份证号
            $param['province']=$row["user_address"];//省份
        }else{
            $row=M("user_face_risk")->where("phone='$order_id'")->find();
            $param['name']=$row["name"];//姓名
            $param['mobile']=$row["phone"];//手机号
            $param['id_card_num']=$row["idcard"];//身份证号
            $param['province']=$row["idcard_address"];//省份
        }

        $row=M("orders")->where("order_id = '$order_id'")->find();

        $param['product_id']="1229915886";//产品id (固定参数) 
        $param['passageway_id']="1229915886";//唯一ID：实例id  (固定参数)
        $param['order_id']=build_order_no();//订单id，用于异步回调推送结果的唯一标示
        $param['company_name']="河南绿悦网络科技有限公司";//公司名称

        $param['access_key']='21df168b02fe4ebaa8dd5d2d5d8c5b83';//公钥
        $param['private_key']='c70ad6ce3fc2462d9fe262068d31fccf';//私钥
        $param['engine_type']=0;
        $param['timeSpan']=date("YmdHis",time());

        $signStr=$param['order_id']."decisionengineIV8LQ1WRWXB7U83AXJ37WG8W3B271G".$param['timeSpan'];
        
        $param['sign']=md5($signStr);


        //自定义参数
        
        $param['token']="abcdef";
        $param['imei']="abcdef123";
        $param['phone_list']=[
                                [
                                    'name'=>"张哥",    
                                    'name'=>"13370644818"   
                                ]

                             ];                           

        //测试地址
        //$url='http://apitest.yuecaifq.com/yc-decision-engine/reDecisionEngine';
        //正式地址  
        $url='http://middle.yuecaijf.com/reDecisionEngine';
        $data["order_id"]=$order_id;
        $data["order_id_number"]=$param['order_id'];
        $data["user_id_number"]=$param['id_card_num'];
        $data["creat_time"]=date("Y-m-d H:i:s",time());
        $count=M("log_yc")->where("order_id='$order_id'")->count();

        if ($count) 
        {
            M("log_yc")->where("order_id='$order_id'")->delete();
        }
        
        M("log_yc")->add($data);

        $param=json_encode($param,JSON_UNESCAPED_UNICODE);
        
        $result=$this->request_post($url,$param);
        
        return json_decode($result,true);
    }
   
    //悦才请求决策 异步回调
    public function reDecisionEngineCallBack()
    {       
        header("Content-type: text/html; charset=utf-8");
        
        $request=file_get_contents("php://input");
        
        //$DOCUMENT_ROOT = "./Public/text.txt";

        $res=json_decode($request,true);

        if ($res['success']) 
        {
           $order_id=$res['order_id'];
           // 值为 1不通过  2异常  3 通过
           $refuse=$res['refuse'];

           $data["is_pass"]=$refuse;
           $data["contents"]=$request;
           M("log_yc")->where("order_id_number = '$order_id'")->save($data);
           
           $this->renderJsonYc("true","操作成功");
        }else{
            $this->renderJsonYc("false","操作失败");
        }

        
        /**
        if (empty($record)) {
            $this->renderJsonYc("false","操作失败");
        }else{
            $this->renderJsonYc("true","操作成功");
        }
            //异步回调 加密 验签
            String sign = req.getParameter("sign"));
            String order_id =req.getParameter("order_id");
            String timeSpan = req.getParameter("timeSpan");
            String DE_APP_KEY="decisionengine";
            String DE_PRIVATE_KEY="IV8LQ1WRWXB7U83AXJ37WG8W3B271G";

            String signMd5 = StringUtil.MD5(order_id + DE_APP_KEY + DE_PRIVATE_KEY + timeSpan).toLowerCase();
            if (sign.equals(signMd5)) {//验签通过
                
            }
        **/

    }



    public function test()
    {   
        $res=$this->reDecisionEngine("2018042107543357529748");
        print_r($res);
    }

    //悦才请求决策 明细
    public function getDecisionEngineReport($order_id_number)
    {   
        header("Content-type: text/html; charset=utf-8");
        $time=date("YmdHis",time());
        
        $param['appKey']="VbLnVxYcyxSstLFqNO";// 固定参数
        $param['appSecrect']="fMG8ZvyJOs60UWsnY3iFcdZgn1XLVSgjE";//固定参数
        $param['order_id']=$order_id_number;//和上面build_order_no()生成的是同一个值 
        $param['product_id']="1229915886";//唯一ID：实例id  (固定参数)
        $param["report_type"]="true";
        $param['timeSpan']=$time;
    
        $str=http_build_query($param);
        
        $signStr=md5($str);
        
        $param['sign']=$signStr;

        unset($param['appSecrect']);
        //测试地址
        //$url='http://apitest.yuecaifq.com/yc-decision-engine/getDecisionEngineReport';
        //正式地址
        $url='https://japc.yuecaijf.com/yc-decision-engine/getDecisionEngineReport';

        $param=json_encode($param,JSON_UNESCAPED_UNICODE);
       
        $result=$this->request_post($url,$param);

        $arr_res=json_decode($result,true);
        
        if ($arr_res["result"] != '') 
        {   
            return $arr_res["resultNote"];
        }else{
            
            return false;
        }
    }


    //同盾 
    public function getTongdunReport()
    {   
        header("Content-type: text/html; charset=utf-8");
        header('Access-Control-Allow-Origin:*');
        
        $id_number=I('idCardNum');
        
        $time=date("YmdHis",time());
        
        $param['appKey']="VbLnVxYcyxSstLFqNO";// 固定参数
        $param['appSecrect']="fMG8ZvyJOs60UWsnY3iFcdZgn1XLVSgjE";//固定参数
        $param['id_number']=$id_number;//身份证号
        $param['timeSpan']=date("YmdHis",time());//

        $str=http_build_query($param);
        
        $signStr=md5($str);
        
        $param['sign']=$signStr;

        unset($param['appSecrect']);
        //测试地址
        //$url='http://apitest.yuecaifq.com/yc-decision-engine/getTongdunReport';
        //正式地址
        $url='https://japc.yuecaijf.com/yc-decision-engine/getTongdunReport';
        $param=json_encode($param,JSON_UNESCAPED_UNICODE);

        $res=$this->request_post($url,$param);
        
        $arr_res=json_decode($res,true);
        
        if ($arr_res["result"] == 'true') 
        {
            echo $arr_res["resultNote"];
        }else{
            echo false;
        }

    }



    private function request_post($url = '', $param = '') 
    {
        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS,$param);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array(
                'Content-Type: application/json; charset=utf-8',
                "Content-Length: " . strlen ( $param )
            ));

        $data = curl_exec($ch);//运行curl
         
        if($data === false)
        {
            return  'Curl error: ' . curl_error($ch);
        }
        
        curl_close($ch);
        
        return $data;
    }




    public function renderJsonYc($status=true,$msg = 'info',$data=array())
    {
        $array = array(
            'result' => $status,
            'message' => $msg,
        );
        exit(json_encode($array,JSON_UNESCAPED_UNICODE));
    }

}